package com.example.yang_app_sixth_server;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;

class ClientThread implements  Runnable{
    public static Handler SendHandler=null;
    Socket sk=null;
    Handler RecHandler=null;
    BufferedReader br=null;
    OutputStream os=null;
    public ClientThread(Handler handler) throws IOException {
        this.RecHandler=handler;
    }

    @Override
    public void run() {
        try {
            sk=new Socket("127.0.0.1",30000);
            System.out.println("yes" );
            br=new BufferedReader(new InputStreamReader(sk.getInputStream()));
            os=sk.getOutputStream();
            new Thread(){
                @Override
                public void run() {
                    String content=null;
                    try {
                        while ((content = br.readLine()) != null) {
                            Message msg = new Message();
                            msg.what = 0x1234;
                            Bundle bundle = new Bundle();
                            bundle.putString("receive_content", content);
                            msg.setData(bundle);

                            RecHandler.sendMessage(msg);

                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Looper.prepare();
        SendHandler=new Handler(){
            @Override
            public void handleMessage(Message msg) {
                if(msg.what==0x1234){
                    try {
                        os.write(msg.getData().getString("send_content").getBytes());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        Looper.loop();

    }
}
